'use strict';
const db = uniCloud.database()
const bannerCollection = db.collection('opendb-banner')

exports.main = async (event, context) => {
	const { action, id } = event
	
	try {
		let res
		switch (action) {
			case 'add':
				// 添加轮播图
				const { title, image, url, sort = 0, status = 1 } = event
				res = await bannerCollection.add({
					title,
					image,
					url,
					sort,
					status,
					create_date: Date.now()
				})
				break
				
			case 'update':
				// 更新轮播图
				const updateData = {}
				['title', 'image', 'url', 'sort', 'status'].forEach(key => {
					if (event[key] !== undefined) {
						updateData[key] = event[key]
					}
				})
				res = await bannerCollection.doc(id).update(updateData)
				break
				
			case 'delete':
				// 删除轮播图
				res = await bannerCollection.doc(id).remove()
				break
				
			default:
				throw new Error('未知的操作类型')
		}
		
		return {
			code: 0,
			msg: '操作成功',
			data: res
		}
	} catch (e) {
		return {
			code: -1,
			msg: e.message
		}
	}
} 